package cn.erhu.basic.multithreading;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 多线程示例
 * <p/>
 */
public class Demo {

    private static final CountDownLatch count_down_latch = new CountDownLatch(3);

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                countDownLatchTest();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                countDownLatchTest();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                countDownLatchTest();
            }
        }).start();

    }

    private static void countDownLatchTest() {

        try {
            doSomethingStupid(count_down_latch);
            count_down_latch.await(60, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void doSomethingStupid(CountDownLatch _count_down_latch) {
        try {
            System.out.println(String.format("我是 %d 号员工，开始干活了，大概要花3秒钟...", Thread.currentThread().getId()));
            // 等待3秒
            Thread.sleep(3000);
            System.out.println(String.format("我是 %d 号员工, 干完活了:)", Thread.currentThread().getId()));

            _count_down_latch.countDown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
